<template>
  <div >
    <!--操作区域-->
    <customForm :data="form" ref="editForm"  :rules="rules" >
      <template #content>
        <customFormItem label="打印服务器" name="printerServerName" :parent="_self" :form="form"
                        :type="constCommon.formItemType.selectStatic.name"
                        :config="{options: printerServers, label: 'name', value: 'id'}"
                        @change="printerServerChange" fullWidth
        />

        <customFormItem label="打印机" name="printerName" :parent="_self" :form="form"
                        :type="constCommon.formItemType.selectStatic.name"
                        :config="{options: cpPrinters, label: 'name', value: 'name'}" fullWidth
                        @change="printerChange"
                        v-show="cpIsPrintLabel"
        />

        <customFormItem label="纸张类型" name="printerSelPage" :parent="_self" :form="form"
                        :type="constCommon.formItemType.selectStatic.name"
                        :config="{options: cpPagelist, label: 'name', value: 'name'}"
                        v-show="cpIsPrintLabel"
                        @change="selectPageChange"
        />

<!--        <customFormItem label="宽高约束" name="isUseWH" :parent="_self" :form="form"
                        :type="constCommon.formItemType.switch.name"
                        :config="{options: constCommon.nobusConst.yesNoBoolean}"
                        help="勾选后，按照指定的宽高进行打印，不勾选：按照纸张名称进行打印"
        />

        <customFormItem label="纸张宽度" name="printerPageWidth" :parent="_self" :form="form"
                        :type="constCommon.formItemType.inputNumber.name"
                        v-show="cpIsUseWH"
                        help="单位毫米"
        />
        <customFormItem label="纸张宽度" name="printerPageHeight" :parent="_self" :form="form"
                        :type="constCommon.formItemType.inputNumber.name"
                        v-show="cpIsUseWH"
                        help="单位毫米"
        />-->

<!--        <customFormItem label="打印方向" name="printerSelOrient" :parent="_self" :form="form"-->
<!--                        :type="constCommon.formItemType.selectStatic.name"-->
<!--                        :config="{options: constCommon.nobusConst.printerSelOrient}"-->
<!--                        v-show="cpIsPrintLabel"-->
<!--        />-->
        <!--


                <customFormItem label="显示预览" name="isShowPre" :parent="_self" :form="form"
                                :type="constCommon.formItemType.switch.name"
                                :config="{options: constCommon.nobusConst.yesNoBoolean}"
                />-->
      </template>
    </customForm>

    <!--操作按钮-->
    <customSpace fullWidth style="text-align: center;margin-top: 9px">
      <template #content>
        <customButton  title="打印"  v-show="cpIsPrint" theme="primary" size="medium" @click="printBefore(false)"/>
        <customButton  title="预览"  v-show="cpIsPrint" theme="primary" size="medium" @click="printBefore(true)"/>
        <customButton  title="保存配置" theme="primary" size="medium" @click="printConfigSave()"/>
        <customButton  title="下载客户端"  theme="default" size="medium" @click="utils.downloadStatic('exe', 'CLodop_Setup_for_Win32NT')"/>
        <customButton  title="关闭" theme="default" size="medium" @click="close"/>
      </template>
    </customSpace>

    <!--打印区域-->
    <div ref="printBox" id="printBox" :class="{'print-box': true, 'print-box-show-pre': false}" >
      <div class="dataTableBox"  v-for="(row,index0) in cpRows" :key="index0" :style="{padding:'0px 0px 0px 5px',width: cpDtBoxWidth}">
        <table style="table-layout:fixed;padding-left: 11px;border-spacing: 0px">
          <tr >
            <td    colspan="2" style="padding: 0px; padding-left: 27px;">
              <FortenCode
                propType="barcode"
                :propValue="row.sn"
                propHeight="40"
                style="zoom: 100%; height: 41px"
              >
              </FortenCode>
              <div style="font-size: 8px; zoom: 100%; line-height: 11px; ">
                {{row.sn}}
                <strong style="padding-left: 3px">{{row.flagOmoc ? '高' : '低'}}</strong>
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="2"  style="padding: 0px;">
              <table style="table-layout:fixed;border-spacing: 0px; padding: 0px">
                <tr>
                  <td :style="getStyle(true)" v-if="!isHide('hrpCode')">
                    编码
                  </td>
<!--                  <td :style="getStyle()" >-->
<!--                    {{row.mscmCode}}({{row.flagOmoc ? '高耗' : '低耗'}})-->
<!--                  </td>-->
                  <td :style="getStyle()" v-if="!isHide('hrpCode')">
                    {{row.hrpCode}}
                  </td>
                  <td :style="getStyle(true)" v-if="!isHide('packageUnit')">
                    包装
                  </td>
                  <td :style="getStyle()" v-if="!isHide('packageUnit')">
                    {{row.packageUnit}}({{row.skuUnit}}/{{row.skuQty}})
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td :style="getStyle(true)" v-if="!isHide('matrName')">
              耗材
            </td>
            <td :style="getStyle()" v-if="!isHide('matrName')">
              <div  :style="getTdMaxWidth()">
                {{row.matrName}}
              </div>
            </td>
          </tr>
          <tr>
            <td :style="getStyle(true)" v-if="!isHide('matrSpec')">
              品规
            </td>
            <td :style="getStyle()" v-if="!isHide('matrSpec')">
              {{row.matrSpec}}
            </td>
          </tr><!--
          <tr>
            <td :style="getStyle(true,true)" v-if="!isHide('sn')">
              SN
            </td>
            <td :style="getStyle()" v-if="!isHide('sn')">
              {{row.sn}}
              <strong style="padding-left: 3px">{{row.flagOmoc ? '高值■' : '低值▲'}}</strong>
            </td>
          </tr>-->
          <tr>
            <td   colspan="2" style="padding: 0px;">
              <table style="table-layout:fixed;border-spacing: 0px; padding: 0px">
                <tr>
                  <td :style="getStyle(true)" v-if="!isHide('lot')">
                    批次
                  </td>
                  <td :style="getStyle()" v-if="!isHide('lot')">
                    {{row.lot}}
                  </td>
                  <td :style="getStyle(true)" v-if="!isHide('expDate')">
                    效期
                  </td>
                  <td :style="getStyle()" v-if="!isHide('expDate')">
                    {{dates.toDate(row.expDate, 'yyyy-MM-dd')}}
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td :style="getStyle(true)" v-if="!isHide('mfgName')">
              厂商
            </td>
            <td :style="getStyle()" v-if="!isHide('mfgName')">
              <div  :style="getTdMaxWidth()">
                {{row.mfgName}}
              </div>
            </td>
          </tr>
          <tr>
            <td :style="getStyle(true)" v-if="!isHide('udi')">
              UDI
            </td>
            <td :style="getStyle(false, false, true)" v-if="!isHide('udi')">
              <div  :style="getTdMaxWidth(true)">
                {{row.udi}}
              </div>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
/*eslint-disable*/
import {getLodop} from '@/util/lodop/LodopFuncs.js'
import LodopModel from '@/util/lodop/LodopModel.js'
import FortenCode from '@/components/common/FortenCode.vue'

let printInstall = true
export default {
  name: 'printForm',
  props: ['param'],
  components: {FortenCode},
  data() {
    return {
      //表格数据
      tableData: [],
      //表格列
      columns: [],
      //隐藏列
      hideColumns: [],
      //Lodop实例,单例
      userLodopModel: null,
      // 打印机列表
      printers: [],

      //打印服务器
      printerServers: [],
      headFootColLabelMax: null,
      //毫米跟像素的换算比率,基本上 1毫米 约等于 3.78像素，此处取整
      mmRatePx: 3.78,

      //数据是否成功加载过一次
      dataLoadOnceSuccess: false,
      form: {
        printerServerId: '',
        printerServerName: '',
        printerServerUrl: '',
        printerName: '',
        printerSelOrient: '',
        printerSelPage: '',
        printerPageWidth: 60,
        printerPageHeight: 40,
        isUseWH: false,
      },
      rules: {
        printerServerName: [{ required: true, message: '打印服务器必须指定', trigger: 'blur' }],
        printerName: [{ required: true, message: '打印机必须指定', trigger: 'blur' }],
        printerSelPage: [{ required: true, message: '纸张类型必须指定', trigger: 'blur' }],
      }
    }
  },
  mounted() {
    this.getPrinterServers()
  },

  computed: {
    isHide() {
      return (col) => {
        if (this.hideColumns && this.hideColumns instanceof Array && this.hideColumns.length > 0) {
          return this.hideColumns.some(hide => hide == col)
        }
        return false
      }
    },
    cpIsUseWH() {
      return this.form.isUseWH
    },
    cpRows() {
      if (this.param && this.param.rows && this.param.rows.length > 0) {
        return this.param.rows
      }
      return []
    },

    // 打印机列表
    cpPrinters() {
      return this.printers
    },

    // 纸张列表
    cpPagelist() {
      if (this.strings.isBlank(this.form.printerName)) {
        return []
      }
      let printIndex = this.cpPrinters.findIndex(item => item.name == this.form.printerName)
      if (printIndex != -1) {
        return this.cpPrinters[printIndex].pagelist
      }
      return []
    },

    // 是否打印
    cpIsPrint() {
      if (!this.param) {
        return false
      }
      let type = this.param.type
      if (!type || type != 'set') {
        return true
      }
      return false
    },

    // 是否普通标签打印
    cpIsPrintLabel() {
      return 'label' == this.form.printerServerType
    },

    // 是否普通标签打印
    cpDtBoxWidth() {
      let printerPageWidth = this.form.printerPageWidth
      if (!printerPageWidth) {
        printerPageWidth = 60
      }
      return printerPageWidth * this.mmRatePx + 'px'
    }
  },
  methods: {
    //关闭窗口
    close(){
      this.$emit("printFormClose")
      console.log('close ', this)
      this.$parent.$parent.hide()
    },
    // 保存打印机配置
    printConfigSave(){
      this.utils.updateUserState('printerLabelConfig', JSON.stringify(this.form), this, true, true)
    },
    // 初始化外部调用
    initOut(){
      let printerLabelConfig = this.utils.loadPrinterLabelConfig(this)
      if (printerLabelConfig) {
        console.log('printerLabelConfig', printerLabelConfig)
        Object.keys(printerLabelConfig).forEach(key => {
          this.$set(this.form, key , printerLabelConfig[key])
        })
      }
      if (this.cpIsPrintLabel) {
        global.utilPrint.isNeedCLodopfuncs(this.form.printerServerUrl,() => {this.initPrintSuccess()})
      }
      if (!this.param) {
        return
      }
      this.hideColumns = this.param.hideColumns
      this.initPrintOnce()
    },

    //初始化打印列表
    async initPrintOnce(){
      // global.utilPrint.isNeedCLodopfuncs(this.param.printServer)
      this.dataLoadOnceSuccess = false
    },

    //初始化打印设置
    initPrintSuccess() {
      var param={
        checkUsable:true
      }
      this.userLodopModel = new window.LodopModel(param);
      if(!this.userLodopModel.lodop && printInstall){
        this.$confirm('未发现可用的打印服务,是否立即下载打印程序？<br><small>确认，下载安装后重新进入打印界面即可。</small><br><small>取消，将关闭打印窗口</small><br><small style="color:#e6a23c">安装时若安全软件提示修改URL关联，请允许</small>', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          this.utils.downloadStatic('exe', 'CLodop_Setup_for_Win32NT')
          printInstall = false
          this.close()
        }).catch(() => {
          printInstall = false
          this.close()
        })
        return false
      } else {
        this.printers = []
        if(this.userLodopModel.lodop){
          //打印机列表
          this.printers = this.userLodopModel.getPrinters()
          if (this.printers.findIndex(item => item.name == '请选择') == -1) {
            this.printers.unshift({name:'请选择'})
          }
        }
      }
    },
    //打服务器选择后
    printerServerChange(selectValue, selectItem) {
      // 更新打印机选择
      this.$set(this.form , 'printerServerUrl' , selectItem.url)
      this.$set(this.form , 'printerServerName' , selectItem.name)
      this.$set(this.form , 'printerServerType' , selectItem.typeKey)
      // 清除其他选项
      Object.keys(this.form).forEach(key => {
        if (['printerName', 'printerSelOrient', 'printerSelPage'].includes(key)) {
          this.$set(this.form , key , '')
        }
      })
      if (this.cpIsPrintLabel) {
        global.utilPrint.isNeedCLodopfuncs(this.form.printerServerUrl,() => {this.initPrintSuccess()})
      }
    },
    //打印机选择后
    printerChange(selectValue, selectItem) {
      // 清除其他选项
      Object.keys(this.form).forEach(key => {
        if ([ 'printerSelPage'].includes(key)) {
          this.$set(this.form , key , '')
        }
      })
    },
    //纸张选择后
    selectPageChange(selectValue, selectItem) {
      let pageSize = global.utilPrint.getPaperSize(selectValue)
      if(!pageSize) {
        this.form.printerPageWidth = 0
        this.form.printerPageHeight = 0
        return
      }
      this.form.printerPageWidth = pageSize.width
      this.form.printerPageHeight = pageSize.height
    },

    //获取表头和表尾标题宽度，取最多标题的宽度
    getHeadFootColLabelMax(){
      if(this.headFootColLabelMax) return this.headFootColLabelMax
      let strMax=''
      if(this.param.head && this.param.head.length>0) {
        this.param.head.forEach(ob =>  {
          if(ob.text.length > strMax.length) strMax = ob.text
        })
      }
      if(this.param.foot && this.param.foot.length>0) {
        this.param.foot.forEach(ob =>  {
          if(ob.text.length > strMax.length) strMax = ob.text
        })
      }
      this.headFootColLabelMax = strMax.length*12+'px'
    },

    //表头表尾列样式
    getHeadFootColStyle(ob){
      let style = {float: 'left', padding: '4px 0px'}
      if(!ob.col) ob.col = 8
      //宽度: 百分比
      let width = ob.col/24*100+'%'
      style.width = width
      style.maxWidth = width
      style.overflowX = 'hidden'
      return style
    },

    //表头列标题样式
    getHeadFootColLabelStyle(ob){
      let style = {float: 'left', fontWeight: 'bold', width: this.headFootColLabelMax }
      return style
    },

    //表格标题列样式
    getDataTableHeadThStyle(column){
      let style = {textAlign: 'center', border: '1px solid black', padding: '3px 6px',minWidth:'30px' }
      return style
    },

    //表格数据列样式
    getDataTableBodyTdStyle(column){
      let style = { border: '1px solid black'}
      // let width = (ob.col/24*100)*this.printerPageWidth*this.mmRatePx
      return style
    },

    //表头表尾数据列样式
    getHeadFootColValueStyle(ob){
      let style = {float: 'left'}
      return style
    },

    //表头表尾数据
    getHeadFootValue(ob){
      if(!ob.value) ob.value = this.param.form[ob.name]
      if(ob.dateFmt &&  ob.value)  ob.value = dates.formatToAnotherPattern(ob.value, ob.dateFmt)
      return ob.value
    },

    //获取列合计
    getColumnSUm(name,pageNum){
      if(name.indexOf('qty') == -1 && name.indexOf('amount') == -1) return ''
      let sum = 0
      this.tableData.forEach( (ob,index) => {
        if ( index>=(pageNum-1)*this.form.printerPageSize &&  index < pageNum*this.form.printerPageSize ) {
          sum+=ob[name]
        }
      })
      return sum
    },

    //打印窗口打开后，数据只查询一次
    async initData() {
      if(this.dataLoadOnceSuccess) return
      let dvParam = this.param.dvParam
      const params = {
        queryString: dvParam.queryString,
        orderString: dvParam.orderString
      }
      this.$ajax.get(dvParam.listEntry, { params }).then((response) => {
        if (response.code == 0) {
          this.tableData = response.data
          this.dataLoadOnceSuccess = true
        }
      })
    },

    getStyle(isLabel,paddingLeft, isWordBreak){
      let style= {fontSize: '11px',wordBreak: 'keep-all',fontWeight: 'bold', whiteSpace: 'nowrap', overflow: 'hidden',zoom:'80%', lineHeight: '11px', height: '11px', maxHeight: '11px'}
      if (isLabel == true )style.width= '30px'
      if (paddingLeft == true )style.paddingLeft= '4px'

      return style
    },

    getTdMaxWidth(isWordBreak){
      let style= {fontSize: '11px',overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', maxWidth: '245px', width: '245px'}
      if (isWordBreak == true ){
        style.whiteSpace= 'normal'
        style.wordBreak= 'break-all'
        style.wordWrap= 'break-word'
        style.overflow= 'visible'
        style.textOverflow= ''
        style.width= '230px'
        style.maxWidth= '230px'
      }
      return style
    },

    //打印或者预览
    printBefore(ispRreview) {
      this.$refs.editForm.validate().then((result) => {
        if (result && result == true) {
          this.print(ispRreview)
        }else {
          this.utilMessage.warning('请先设置好打印机必填项')
        }
      })
    },

    //打印或者预览
    async print(ispRreview) {
      if (this.strings.isBlank(this.form.printerServerName)) {
        this.utilMessage.warning('请选择打印服务器')
        return
      }
      if (this.strings.isBlank(this.form.printerName)) {
        this.utilMessage.warning('请选择打印机')
        return
      }
      if (this.strings.isBlank(this.form.printerSelPage)) {
        this.utilMessage.warning('请选择纸张')
        return
      }

      this.utilVue.loadShow(true)
      let that = this
      setTimeout( () => {
        //分页
        $('.pagebreak').remove()
        let dataTableNum = $('.dataTableBox').length
        if(dataTableNum >1){
          // $('.dataTableBox').after('<p class="pagebreak" style="page-break-after:always;    height: 0px;padding: 0px;margin: 0px;">&nbsp;&nbsp;&nbsp;</p>')
          // $('.pagebreak:last').remove()
        }

        //设置打印机属性
        this.userLodopModel.printerName = that.form.printerName
        // this.userLodopModel.printerPageWidth = that.form.printerPageWidth
        // this.userLodopModel.printerPageHeight = that.printerPageHeight

        // this.userLodopModel.printerOrient = this.form.printerSelOrient

        this.userLodopModel.printerPage = that.form.printerSelPage


        // let printBox = $(that.$refs.printBox)
        // this.userLodopModel.addPrintHtml(printBox.prop("outerHTML"))

        //设置对象在纸张范围内水平居中,
        // this.userLodopModel.lodop.SET_PRINT_STYLEA(0,"Horient",2)


        let childLength = $('.dataTableBox').length

        try {
          $('.dataTableBox').each((index, element) => {
            this.userLodopModel.addPrintHtml($(element).prop("outerHTML"))
            if (index != childLength - 1) {
              this.userLodopModel.lodop.NewPage()
            }
          })
        }catch (e) {
          console.error('e', e)
        }

        //LODOP.NewPage();

        let retMsg = null
  /*      if (!retMsg) {
          this.utilVue.loadHide()
          return
        }*/
        if (ispRreview) {
          this.utilVue.loadHide()
          //预览窗口已打开
          if(this.userLodopModel.lodop.OBO_Mode && this.userLodopModel.lodop.blOneByone) {
            global.utilMessage.alertFail(`预览窗口已打开，请到任务栏找到打印预览图标进行关闭，然后重新尝试预览操作`, '系统提示', {
              confirmButtonText: '确定',
              type: 'warning',
              callback: action => {
              }
            })
            retrun
          }
          retMsg = this.userLodopModel.printView()
          //打印次数
          // let snArr = []
          // that.param.rows.forEach(ob => {snArr.push(ob.sn)})
          // global.utilPrint.updatePrintNum(snArr)
        } else {
          // retMsg = this.userLodopModel.print()

          this.userLodopModel.setPrinter()
          this.userLodopModel.lodop.SET_PRINT_MODE("CATCH_PRINT_STATUS",true)


          let printValue = null
          let that = this

          this.userLodopModel.lodop.On_Return=function(TaskID,Value){
            printValue = Value

            var strResult
            try{
              strResult=that.userLodopModel.lodop.GET_VALUE('PRINT_STATUS_ID',printValue)
            }catch (e) {
              console.error('GET_VALUE',e)
            }
            setTimeout(() => {
              that.utilMessage.success('打印任务已提交')
              that.utilVue.loadHide()
            }, 1000)

          };
          let ret = this.userLodopModel.lodop.PRINT();
          //打印次数
          let snArr = []
          that.param.rows.forEach(ob => {snArr.push(ob.sn)})
          global.utilPrint.updatePrintNum(snArr)
        }
      },1000)
    },

    //查询打印服务器
    getPrinterServers(){
      let wrapper = this.$newWrapper()
      wrapper.eq('typeKey', 'rfid').or('typeKey', 'label')
      const params = {
        queryString: this.utils.json2str(wrapper.queryConditions)
      }
      this.$ajax.get('/sys/printer/list',{params}).then(resp => {
        if (resp.code == 0) {
          this.printerServers = resp.data
          this.printerServers.unshift({name:'请选择',id: ''})
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
  .container{
    padding: 5px;
  }
  .print-box {
    border: 3px dotted #1890FF;
    overflow-x: auto;
    position: absolute;
    top: -999999999px;
  }

  .print-box-show-pre{
    position: relative;
    top: 0px;
  }
</style>
